<script setup lang="ts">
import Table from '@/components/table/index.vue';
import useGetList from '@/hooks/useGetList';
import { getModelRecords, GetModelRecordParams, ModelRecord, activeModelById } from '@/services/data';
import { ElMessage, ElMessageBox } from 'element-plus';

interface Props {
  // visible: boolean;
  active: boolean;
}

// interface Emits {
//   (e: "update:visible", visible: boolean): void;
// }

const getListFC = async (params: GetModelRecordParams) => {
  try {
    const res = await getModelRecords(params);
    const { page, length } = params;
    return {
      list: (res.list || []).map((record, idx) => ({
        ...record,
        index: idx + 1 + (page - 1) * length,
      })),
      total: res.total || 0,
      page: params.page || 1,
      size: params.length || 15,
    };
  } catch {
    return {
      list: [],
      total: 0,
      page: 1,
      size: 15,
    };
  }
};

const props = defineProps<Props>();
const {
  list,
  getList,
  loading,
  total,
  page,
  size,
} = useGetList(getListFC);

const handleApplyModel = async (row: any) => {
  await ElMessageBox.confirm(`确定应用版本号为 ${row.name} 的姿态模型吗？`, '姿态模型应用', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'info',
  });
  try {
    await activeModelById(row.id);
    ElMessage({
      type: 'success',
      message: '操作成功',
    });
    handleQuery(1, size.value);
  } catch {
    ElMessage({
      type: 'warning',
      message: '操作失败，请重试',
    });
  }
};

const columns = [
  {
    prop: 'index',
    label: '序号',
    align: 'center',
    width: 80,
  },
  // {
  //   prop: 'dbname',
  //   label: '文件名称',
  //   align: 'center',
  //   width: 120,
  // },
  {
    prop: 'created_time',
    label: '完成时间',
    align: 'center',
  },
  {
    prop: 'name',
    label: '版本号',
    align: 'center',
  },
  {
    label: '操作',
    align: 'center',
    width: 120,
    // fixed: 'right',
    renderBtns: [
      {
        text: '应用',
        onClick: (_idx: number, row: ModelRecord) => handleApplyModel(row),
        type: 'primary',
        link: true,
        disableFn: (_idx: number, row: ModelRecord) => !!row.active,
        textFn: (_idx: number, row: ModelRecord) => {
          if (row.active) {
            return '应用中';
          } else {
            return '应用';
          }
        },
      },
    ]
  },
];

const handleQuery = (page: number, length: number) => {
  getList({ page, length });
};

onMounted(() => {
  handleQuery(1, size.value);
});
</script>

<template>
  <Table
    v-if="props.active"
    :loading="loading"
    :list="list"
    border
    height="calc(100vh - 35px - 62px - 50px - 40px - 60px)"
    :columns="columns"
    :total="total"
    :page-no="page"
    :page-size="size"
    :get-list="(pageNo: number, pageSize: number) => handleQuery(pageNo, pageSize)"
  />
</template>

<style lang="less" scoped>
</style>
